package com.example.administrator.zkdemo.controller;

/**
 * Created with Android Studio.
 * 描述: ${DESCRIPTION}
 * Date: 2018/11/20
 * Time: 14:53
 *
 * @author 晏琦云
 * @version ${VERSION}
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.util.Log;
import android.view.SurfaceView;

import com.sensetime.mid.faceapi.FaceSearch;
import com.sensetime.mid.faceapi.FaceVerify;
import com.sensetime.mid.faceapi.model.FaceInfo;
import com.sensetime.mid.faceapi.model.FaceSearchResult;
import com.sensetime.mid.faceapi.util.FaceDrawUtil;
import com.sensetime.senseguardsdk.FaceDetector;
import com.sensetime.senseguardsdk.FaceUtils;
import com.sensetime.senseguardsdk.LiveDetector;
import com.sensetime.senseguardsdk.Orientation;
import com.sensetime.senseguardsdk.SDKManager;
import com.sensetime.senseguardsdk.SDKManager.SDKInitListener;
import com.sensetime.senseguardsdk.Verifier;
import com.sensetime.senseguardsdk.Verifier.Builder;
import com.zkteco.android.db.orm.manager.DataManager;
import com.zkteco.android.db.orm.tna.PersBiotemplate;
import com.zkteco.android.db.orm.tna.PersBiotemplatedata;
import com.zkteco.android.db.orm.tna.UserInfo;
import com.zkteco.android.utils.ZKCameraTextureView;

import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FaceController {
    private static FaceController faceController;
    private static ExecutorService mWorkerThreads = Executors.newFixedThreadPool(3);
    private final String TAG = "FaceController";
    public boolean isPaused = false;
    private ZKCameraTextureView mCameraView;
    private Context mContext;
    public byte[] mFaceData;
    private FaceDetector mFaceDetector;
    public boolean mFaceGetReady = false;
    private FaceInfo[] mFaceInfoes = new FaceInfo[10];
    private FaceVerify mFaceVerify;
    private LiveFaceListener mListener;
    private float mLiveConfidence;
    private LiveDetector mLiveDetector;
    private Future mLoadThread;
    private Object mLock = new Object();
    public byte[] mNv21;
    public boolean mNv21GetReady = false;
    private SurfaceView mOverlapView;
    public Paint mPaint = new Paint();
    private Future mRecognizeThread;
    private Future mTrackThread;
    private Verifier mVerifier;
    private int threshold;

    static {
        faceController = new FaceController();
    }

    private FaceController() {
        this.mPaint.setColor(Color.rgb(0, 255, 0));
        this.mPaint.setStyle(Paint.Style.STROKE);
    }

    private void clearCanvas() {
        Canvas localCanvas = this.mOverlapView.getHolder().lockCanvas();
        if (localCanvas != null) {
            localCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
            this.mOverlapView.getHolder().unlockCanvasAndPost(localCanvas);
        }
    }

    private void drawFaces(FaceInfo[] paramArrayOfFaceInfo) {
        if (paramArrayOfFaceInfo != null) {
            Canvas localCanvas = this.mOverlapView.getHolder().lockCanvas();
            if (localCanvas == null)
                return;
            PorterDuff.Mode localMode = PorterDuff.Mode.CLEAR;
            int i = 0;
            localCanvas.drawColor(0, localMode);
            localCanvas.save();
            localCanvas.setMatrix(this.mCameraView.getMatrix());
            int j = paramArrayOfFaceInfo.length;
            while (i < j) {
                FaceDrawUtil.drawFaceRect(localCanvas, paramArrayOfFaceInfo[i].faceRect, this.mPaint);
                i += 1;
            }
            localCanvas.restore();
            this.mOverlapView.getHolder().unlockCanvasAndPost(localCanvas);
            return;
        }
        clearCanvas();
    }

    public static FaceController getInstance() {
        return faceController;
    }

    public void bindCameraView(ZKCameraTextureView paramZKCameraTextureView) {
        this.mCameraView = paramZKCameraTextureView;
    }

    public void bindOverView(SurfaceView paramSurfaceView) {
        this.mOverlapView = paramSurfaceView;
    }

    public FaceDetector getFaceDetector() {
        return this.mFaceDetector;
    }

    public FaceVerify getFaceVerify() {
        return this.mFaceVerify;
    }

    public LiveDetector getLiveDetector() {
        return this.mLiveDetector;
    }

    public Verifier getVerifier() {
        return this.mVerifier;
    }

    public void init(Context paramContext) {
        this.mContext = paramContext.getApplicationContext();
        SDKManager.init(this.mContext, new SDKManager.SDKInitListener() {
            public void onFailed(int paramInt, String paramString) {
                StringBuilder localStringBuilder = new StringBuilder();
                localStringBuilder.append("证书校验失败:");
                localStringBuilder.append(paramInt);
                localStringBuilder.append(",");
                localStringBuilder.append(paramString);
                Log.d("FaceController", localStringBuilder.toString());
                FaceController.this.mListener.onInitFailed();
            }

            public void onStart() {
            }

            public void onSucceed() {
                Log.d("FaceController", "证书校验成功");
                FaceController.access$002(FaceController.this, (Verifier) new Verifier.Builder(FaceController.this.mContext).setOrientation(Orientation.LANDSCAPE).setPreviewSize(1920, 1080).build());
                FaceController.access$202(FaceController.this, (FaceDetector) new FaceDetector.Builder().setOrientation(Orientation.LANDSCAPE).setPreviewSize(1920, 1080).build());
                FaceController.access$302(FaceController.this, (LiveDetector) new LiveDetector.Builder(FaceController.this.mContext).setOrientation(Orientation.LANDSCAPE).setPreviewSize(1920, 1080).build());
                FaceController.access$402(FaceController.this, new FaceVerify());
                FaceController.access$502(FaceController.this, FaceController.mWorkerThreads.submit(new FaceController.TrackTask(FaceController.this)));
                FaceController.access$702(FaceController.this, FaceController.mWorkerThreads.submit(new FaceController.FaceRecognizeTask(FaceController.this, null)));
                FaceController.this.mListener.onSdkInitSucceed();
            }
        });
    }

    public void insertFeature(String paramString, Bitmap paramBitmap) {
        try {
            synchronized (this.mLock) {
                paramBitmap = this.mVerifier.getFeature(paramBitmap);
            }
        } catch (Exception paramBitmap) {
            paramBitmap.printStackTrace();
            paramBitmap = null;
            if (paramBitmap != null) {
                Object localObject1 = new UserInfo();
                try {
                    paramString = (UserInfo) ((UserInfo) localObject1).getQueryBuilder().where().eq("User_PIN", paramString).queryForFirst();
                    try {
                        Log.i("FaceController", "insertFeature ===== true");
                    } catch (SQLException localSQLException1) {
                    }
                } catch (SQLException localSQLException2) {
                    paramString = (String) localObject1;
                }
                Log.i("FaceController", "insertFeature ===== err");
                localSQLException2.printStackTrace();
                if (paramString != null)
                    try {
                        DataManager localDataManager = new DataManager();
                        localDataManager.open(this.mContext);
                        FaceSearch.delete((int) paramString.getID());
                        int i = FaceSearch.insert((int) paramString.getID(), paramBitmap);
                        localObject1 = new StringBuilder();
                        ((StringBuilder) localObject1).append("insertFeature ===== ");
                        ((StringBuilder) localObject1).append(i);
                        Log.i("FaceController", ((StringBuilder) localObject1).toString());
                        localObject1 = (PersBiotemplate) new PersBiotemplate().getQueryBuilder().where().eq("User_PIN", paramString.getUser_PIN()).queryForFirst();
                        if (localObject1 != null) {
                            localDataManager.executeSql("ZKDB.db", "update Pers_BioTemplateData set template_data=?, CREATE_ID=?, MODIFY_TIME=?, SEND_FLAG=? WHERE ID=?", new Object[]{paramBitmap, Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), Long.valueOf(((PersBiotemplate) localObject1).getTemplate_id())});
                        } else {
                            localDataManager.executeSql("ZKDB.db", "insert into Pers_BioTemplateData(template_data,CREATE_ID, MODIFY_TIME, SEND_FLAG) values(?,?,?,?)", new Object[]{paramBitmap, Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)});
                            long l = ((PersBiotemplatedata) new PersBiotemplatedata().getQueryBuilder().orderBy("ID", false).queryForFirst()).getID();
                            paramBitmap = new PersBiotemplate();
                            paramBitmap.setTemplate_id((int) l);
                            paramBitmap.setUser_pin(paramString.getUser_PIN());
                            paramBitmap.setBio_type(2);
                            paramBitmap.setMajor_ver(8);
                            paramBitmap.setTemplate_no(1);
                            paramBitmap.create();
                        }
                    } catch (Exception paramString) {
                        paramString.printStackTrace();
                    }
            }
            monitorexit;
            return;
        }
        monitorexit;
    }

    public void setLiveConfidence(float paramFloat) {
        this.mLiveConfidence = paramFloat;
    }

    public void setLiveFaceListener(LiveFaceListener paramLiveFaceListener) {
        this.mListener = paramLiveFaceListener;
    }

    public void setThreshold(int paramInt) {
        this.threshold = paramInt;
    }

    public void start() {
        if (this.mTrackThread == null)
            this.mTrackThread = mWorkerThreads.submit(new TrackTask());
        if (this.mRecognizeThread == null)
            this.mRecognizeThread = mWorkerThreads.submit(new FaceRecognizeTask(null));
    }

    public void stop() {
        this.isPaused = true;
        if (this.mTrackThread != null)
            this.mTrackThread.cancel(true);
        if (this.mRecognizeThread != null)
            this.mRecognizeThread.cancel(true);
        this.mTrackThread = null;
        this.mRecognizeThread = null;
        if (this.mCameraView != null)
            this.mCameraView = null;
        if (this.mListener != null)
            this.mListener = null;
        if (this.mOverlapView != null)
            this.mOverlapView = null;
    }

    private class FaceRecognizeTask extends Thread {
        private FaceRecognizeTask() {
        }

        public void run() {
            while (!FaceController.this.isPaused) {
                if (!FaceController.this.mFaceGetReady)
                    continue;
                if (FaceController.this.mFaceInfoes != null) {
                    FaceInfo[] arrayOfFaceInfo1 = FaceController.this.mFaceInfoes;
                    j = arrayOfFaceInfo1.length;
                    i = 0;
                    while (i < j) {
                        Object localObject3 = arrayOfFaceInfo1[i];
                        if (localObject3 != null) {
                            float f = FaceController.this.mLiveDetector.detect(FaceController.this.mFaceData, (FaceInfo) localObject3);
              ??? =new StringBuilder();
                            ((StringBuilder) ? ??).append("run: liveConfidence=");
                            ((StringBuilder) ? ??).append(f);
                            Log.i("FaceController", ((StringBuilder) ? ? ?).toString());
                            if (f < FaceController.this.mLiveConfidence)
                                synchronized (FaceController.this.mLock) {
                                    localObject3 = FaceController.this.mVerifier.getFeature(FaceController.this.mFaceData, (FaceInfo) localObject3);
                                    if (localObject3 != null) {
                                        localObject3 = FaceSearch.search(FaceController.this.mFaceVerify, localObject3);
                                        if (localObject3 != null) {
                                            StringBuilder localStringBuilder = new StringBuilder();
                                            localStringBuilder.append("run: result=");
                                            localStringBuilder.append(((FaceSearchResult) localObject3).toString());
                                            Log.i("FaceController", localStringBuilder.toString());
                                            if (((FaceSearchResult) localObject3).score * 100.0F > FaceController.this.threshold)
                                                FaceController.this.mListener.onFaceRecognized((FaceSearchResult) localObject3);
                                        }
                                    }
                                }
                        }
                        i += 1;
                    }
                }
                FaceInfo[] arrayOfFaceInfo2 = FaceController.this.mFaceInfoes;
                int j = arrayOfFaceInfo2.length;
                int i = 0;
                while (i < j) {
          ??? =arrayOfFaceInfo2[i];
                    i += 1;
                }
                FaceController.this.mFaceGetReady = false;
            }
        }
    }

    public class TrackTask extends Thread {
        public TrackTask() {
        }

        public void run() {
            while (!FaceController.this.isPaused) {
                if (!FaceController.this.mNv21GetReady)
                    continue;
                FaceInfo[] arrayOfFaceInfo = FaceController.this.mFaceDetector.detectOrderByFaceWidth(FaceController.this.mNv21);
                if (arrayOfFaceInfo == null) {
                    FaceController.this.clearCanvas();
                    FaceController.this.mNv21GetReady = false;
                    continue;
                }
                if (FaceController.this.mListener.onFindFace()) {
                    FaceController.this.clearCanvas();
                    continue;
                }
                FaceController.this.drawFaces(arrayOfFaceInfo);
                if (!FaceController.this.mFaceGetReady) {
                    int i;
                    if (arrayOfFaceInfo.length < FaceController.this.mFaceInfoes.length)
                        i = arrayOfFaceInfo.length;
                    else
                        i = FaceController.this.mFaceInfoes.length;
                    int j = 0;
                    while (j < i) {
                        FaceInfo localFaceInfo = FaceUtils.clone(arrayOfFaceInfo[j]);
                        FaceController.this.mFaceInfoes[j] = localFaceInfo;
                        j += 1;
                    }
                    System.arraycopy(FaceController.this.mNv21, 0, FaceController.this.mFaceData, 0, FaceController.this.mNv21.length);
                    FaceController.this.mFaceGetReady = true;
                }
                FaceController.this.mNv21GetReady = false;
            }
        }
    }
}
